/*
大厅场景的主要逻辑
*/
var confige = require("confige");

cc.Class({
    extends: cc.Component,

    properties: {
        head_sprite:{
            default:null,
            type:cc.Sprite
        },

        id_label:{
            default:null,
            type:cc.Label
        },

        cardNum_label:{
            default:null,
            type:cc.Label
        },

        nick_label:{
            default:null,
            type:cc.Label
        }
    },

    // use this for initialization

    onLoad: function () {
        window.DKTools.audioEG.playBg("hallBgm");
        window.clientGlobal.loadingNode.hideLayer();
        confige.isBalcony = false;

        confige.gameSceneLoadOver = false;
        confige.gameSceneLoadData = [];
        // confige.loadNode.hideNode();

        this.topNode = this.node.getChildByName("topNode");
        this.bottomNode = this.node.getChildByName("bottomNode");
        this.moreBtnNode = this.node.getChildByName("moreBtnNode");

        this.btnAddCard = this.topNode.getChildByName("cardNode").getChildByName("btnAdd").getComponent("cc.Button");
        this.btnAddCard.interactable = true;

        this.btnAdmin = this.moreBtnNode.getChildByName("btnAdmin");
        this.btnRoomHis = this.moreBtnNode.getChildByName("btnRoomHis");
        if(window.localSetting.roomHistoryCount > 0)
        {
            this.joinRoomHistory = this.node.getChildByName("joinRoomHistory").getComponent("joinRoomHistory");
            this.joinRoomHistory.onInit();
        }

        this.btnBankerAdmin = this.bottomNode.getChildByName("btnBankerAdmin");
        
        if(confige.userInfo.limits >= 2)
        {
            this.adminLayer = this.node.getChildByName("adminLayer").getComponent("adminLayer");
            this.adminLayer.onInit();
        }

        if(cc.sys.platform == cc.sys.MOBILE_BROWSER)
        {
            this.h5ShareNode = this.node.getChildByName("h5Share");
            this.h5ShareNode.opacity = 0;
            this.h5ShareNode.active = false;
            this.check_inviteCode();

            this.topNode.getChildByName("cardNode").getChildByName("btnAddCard").active = false;
            confige.oriPaomaText = "和谐游戏，拒绝赌博，如若发现，封号并提交公安机关处理。";
        }

        pomelo.clientScene = this;
        confige.curGameScene = this;
        confige.curSceneIndex = 1;
        confige.curReconnectType = confige.ON_HALL;
        
        // this.userNode = this.topNode.getChildByName("userNode");
        // this.nickName = this.userNode.getChildByName("nickName").getComponent("cc.Label");
        // this.id = this.userNode.getChildByName("id").getComponent("cc.Label");
        // this.cardNum = this.topNode.getChildByName("cardNode").getChildByName("");

        this.nick_label.string = confige.userInfo.nickname;
        this.id_label.string = "ID:"+confige.userInfo.playerId;
        this.cardNum_label.string = confige.curDiamond;
        
        this.userInfoLayer = this.node.getChildByName("userInfoLayer").getComponent("userInfoLayer");
        this.userInfoLayer.onInit();
        this.userInfoLayer.setUserInfo(confige.userInfo.nickname,confige.userInfo.playerId);
        if(confige.meWXHeadFrame != -1)
        {
            cc.log("fuck change head img");
            this.head_sprite.spriteFrame = confige.meWXHeadFrame;
            this.userInfoLayer.setMainHeadFrame();
        }

        this.paoma = this.topNode.getChildByName("paoma").getChildByName("content").getChildByName("New Label");
        this.paomaLabel = this.paoma.getComponent("cc.Label")
        this.paomaOriText = confige.oriPaomaText;
        this.paomaLabel.string = this.paomaOriText;
        this.paomaTextList = [];
        this.paomaAddOneText(-1);

        this.joinLayer = this.node.getChildByName("joinLayer").getComponent("joinLayer");
        this.joinLayer.onInit();
        this.createLayer = this.node.getChildByName("createLayer").getComponent("createLayer");
        this.createLayer.onInit();
        this.createLayer.parent = this;

        this.shopLayer = this.node.getChildByName("shopLayer").getComponent("shopLayer");
        this.shopLayer.onInit();
        this.settingLayer = this.node.getChildByName("settingLayer").getComponent("settingLayer");
        this.settingLayer.onInit();
        this.historyLayer = this.node.getChildByName("historyLayer").getComponent("historyLayer");
        this.historyLayer.onInit();
        this.shareLayer = this.node.getChildByName("shareLayer").getComponent("shareLayer");
        this.shareLayer.onInit();
        this.ruleLayer = this.node.getChildByName("ruleLayer").getComponent("ruleLayer");
        this.ruleLayer.onInit();
        this.noticeLayer = this.node.getChildByName("noticeLayer");
        this.clubTips = this.node.getChildByName("clubTips");
        if(cc.sys.localStorage.getItem('show_tips') == null){
            this.noticeLayer.active = true;
            cc.sys.localStorage.setItem('show_tips',false);
        }
        this.moreGameLayer = this.node.getChildByName("moreGameLayer");
        this.identification = this.node.getChildByName("identification").getComponent("identification");

        this.btnClub = this.node.getChildByName("btnClub").getComponent("cc.Button");
        this.clubLayer = this.node.getChildByName("clubLayer").getComponent("clubLayer");
        this.clubLayer.onInit();
        this.roomInfoLayer = this.node.getChildByName("roomInfoLayer").getComponent("roomInfoLayer");
        this.roomInfoLayer.onInit();
        this.roomInfoLayer.parent = this;
    },
    
    start:function(){
        if(confige.firstShowNotice == true)
        {
            console.log("fuck firstShowNotice!!!!!!!");
            this.onBtnShowNotice();
            confige.firstShowNotice = false;
            var curDate = new Date();
            var lastLoginDate = {
                year : curDate.getFullYear(),
                month : curDate.getMonth() + 1,
                day : curDate.getDate()
            }
            cc.sys.localStorage.setItem('lastLoginDate', JSON.stringify(lastLoginDate));
        }

        var infoCount = confige.hallSceneLoadData.length;
        console.log(confige.hallSceneLoadData);
        for(var i=0;i<infoCount;i++)
        {
            console.log("deal once!!!!!!!!");
            var curInfo = confige.hallSceneLoadData.shift();
            pomelo.dealWithOnNotify(curInfo);
            console.log(curInfo);
        }
        confige.hallSceneLoadData = [];
    },

    paomaAddOneText:function(textData,paomaTime){
        if(textData != -1)
        {
            this.paomaTextList.push(textData);
            this.paoma.x = 250;
            this.paomaLabel.string = textData;
            console.log("curPaomaString = " + textData);
            this.paoma.stopAllActions();
        }

        var paomaCurMoveX = -(this.paoma.width + 250 + 700);
        var paomaCurMoveT = 15;
        var paomaCurMove = cc.moveBy(paomaCurMoveT, paomaCurMoveX, 0);

        var finished = function(){//cc.callFunc(function () {
            if(this.paomaTextList.length == 0)
            {
                this.paomaLabel.string = this.paomaOriText;
            }else{
                this.paomaLabel.string = this.paomaTextList[this.paomaTextList.length-1];
                this.paomaTextList.pop();
            }
            this.paoma.x = 250;
            paomaCurMoveX = -(this.paoma.width + 250 + 700);
            paomaCurMoveT = (-paomaCurMoveX) / 200 + 2;
            if(paomaCurMoveT < 10)
                paomaCurMoveT = 10;
            if(paomaTime)
            {
                var setX = cc.callFunc(function () {
                    this.paoma.x = 250;
                },this);
                var moveAction = cc.moveBy(paomaCurMoveT, paomaCurMoveX, 0);
                paomaCurMove = cc.repeat(cc.sequence(setX, moveAction), paomaTime);
            }else{
                paomaCurMove = cc.moveBy(paomaCurMoveT, paomaCurMoveX, 0);
            }
        }.bind(this);
        
        finished();

        var paomaCallFunc = cc.callFunc(function () {
            this.paoma.stopAllActions();
            finished();
            this.paoMaSeq = cc.sequence(
                paomaCurMove,
                paomaCallFunc
            );
            this.paoma.runAction(this.paoMaSeq);
        },this);     

        this.paoMaSeq = cc.sequence(
            paomaCurMove,
            paomaCallFunc
        );
        this.paoma.runAction(this.paoMaSeq);
    }, 

    onBtnShowLayer:function(event, customEventData){
        var self = this;
        window.DKTools.audioEG.playEffect("tips_btnClick");
        var index = parseInt(customEventData);
        switch(index){
            case 1:
            console.log("打开战绩界面");
            this.historyLayer.showLayer();
            break;
            case 2:
            console.log("打开商城界面");
            // this.shopLayer.showLayer();
            cc.sys.openURL(confige.wxAppInfo.payURL);
            break;
            case 3:
            console.log("打开信息界面");
            this.noticeLayer.active = true;
            break;
            case 4:
            console.log("打开设置界面");
            var isHall = true
            this.settingLayer.showLayer(isHall);
            break;
            case 5:
            console.log("打开分享");
            this.shareLayer.showLayer();
            break;
            case 6:
            console.log("打开创建房间界面");
            this.createLayer.showLayer(4,true);
            break;
            case 7:
            console.log("打开加入房间界面");
            this.joinLayer.showLayer();
            break;
            case 8:
            console.log("显示玩家信息界面")
            this.userInfoLayer.showLayer();
            break;
            case 9:
            console.log("显示棋牌风情街");
            this.moreGameLayer.active = true;
            break;
            case 10:
            console.log("隐藏棋牌风情街");
            this.moreGameLayer.active = false;
            break;
            case 11:
            console.log("打开规则界面");
            this.ruleLayer.showLayer();
            break;
            case 12:
            console.log("打开群主管理界面");
            if(confige.userInfo.clubLimit == "1"){
                pomelo.request("connector.club.getClubList",null, function(data) {
                    console.log(data);
                    self.clubLayer.showLayer();
                    self.clubLayer.reloadClubData(data);
                });
            }else{
                window.clientGlobal.tipsBox.showLayer(1,"您还不是群主,请联系游戏管理员!");
            }
            break;
            case 13:
            console.log("打开代开房界面");
            this.roomInfoLayer.showLayer();
            break;
            case 14:
            //show moreBtnNode
            this.moreBtnNode.stopAllActions();
            this.moreBtnNode.runAction(cc.scaleTo(0.3,1));
            break;
            case 15:
            //hide moreBtnNode
            this.moreBtnNode.stopAllActions();
            this.moreBtnNode.runAction(cc.scaleTo(0.3,0));
            break;
            default:
            break;
        };
    },

    btnMoreGameClick:function(event, customEventData){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        var index = parseInt(customEventData);
        this.createLayer.showLayer(index,true);
    },

    onBtnShowNotice:function(){
        return;
        var self = this;
        pomelo.request("connector.entryHandler.getNotify",null, function(data) {
            confige.noticeData = data;
            console.log(data);
            self.noticeLayer.addNotice(data);
            self.noticeLayer.showLayer();
        });
    },

    onBtnGameExit:function(event, customEventData){   
        if(confige.curUsePlatform == 3){
            confige.curGameScene.destroy();
            window.close();
        }
        cc.director.end();
        console.log("game exit->run()");
        if(confige.curUsePlatform == 2)
            jsb.reflection.callStaticMethod("JSCallOC","GameExit");
        //可能需要针对不同的平台做不同的处理，并且在end之前要向服务器发送下线
    },

    hideH5ShareNode:function(){
        this.h5ShareNode.stopAllActions();
        this.h5ShareNode.opacity = 0;
        this.h5ShareNode.active = false;
    },
    
    btnAddDiamond:function(){
        if(cc.sys.platform == cc.sys.MOBILE_BROWSER)
            return;
        cc.sys.openURL(confige.wxAppInfo.payURL);
    },

    updateDiamond:function(){
        this.cardNum_label.string = confige.curDiamond;
        // this.diamondNum.string = confige.curDiamond;
    },

    update: function (dt) {
        window.GVoice.gvoicePoll();
    },

    check_invite:function(){
        var self = this;
        var xmlHttp = this.createXMLHttpRequest();
        var httpCallback = function(){
            if (xmlHttp.readyState==4)
              {// 4 = "loaded"
              if (xmlHttp.status==200)
                {// 200 = OK
                    var curReturn = JSON.parse(xmlHttp.responseText);
                    console.log(curReturn);
                    if(curReturn.errcode == 0)
                        self.btn_invite.interactable = false;
                    else
                        self.onBtnShowLayer(6);
                }
              else
                {
                    console.log("Problem retrieving XML data");
                    self.btn_invite.interactable = false;
                }
              }
        };

        this.scheduleOnce(function() {
            var url = "http://qiadmin.njhuajia.com/niu_admin.php/Api/checkAgent?";
            url = url + "game_uid=" + confige.userInfo.playerId;
            console.log("url====="+ url);
            xmlHttp.onreadystatechange = httpCallback;
            xmlHttp.open("GET", url, true);// 异步处理返回   
            xmlHttp.setRequestHeader("Content-Type",  
                    "application/x-www-form-urlencoded;");  
            xmlHttp.send();
        }, 0.25);
    },

    check_inviteCode:function(){
        var self = this;
        var xmlHttp = this.createXMLHttpRequest();
        var httpCallback = function(){
            if (xmlHttp.readyState==4)
            {// 4 = "loaded"
                if (xmlHttp.status==200)
                {// 200 = OK
                  var curReturn = JSON.parse(xmlHttp.responseText);
                  console.log(curReturn);
                  if(curReturn.errcode == 0){
                        confige.h5InviteCode = curReturn.invite_code;
                        console.log("invite_code ===" + curReturn.invite_code);
                  }else{
                        console.log("invite_code ===0000");
                  }
                  self.h5ShareInit();
                }
            }
            
        };

        this.scheduleOnce(function() {
            var url = "http://qiadmin.njhuajia.com/niu_admin.php/Api/getInviteCode?game_uid="+confige.userInfo.playerId;
            console.log("url====="+ url);
            xmlHttp.onreadystatechange = httpCallback;
            xmlHttp.open("GET", url, true);// 异步处理返回   
            xmlHttp.setRequestHeader("Content-Type",  
                    "application/x-www-form-urlencoded;");  
            xmlHttp.send();
        }, 0.1);
    },

    createXMLHttpRequest:function() {  
        var xmlHttp;  
        if (window.XMLHttpRequest) {  
            xmlHttp = new XMLHttpRequest();  
            if (xmlHttp.overrideMimeType)  
                xmlHttp.overrideMimeType('text/xml');  
        } else if (window.ActiveXObject) {  
            try {  
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");  
            } catch (e) {  
                try {  
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
                } catch (e) {  
                }  
            }  
        } 
        return xmlHttp;  
    },

    openShare:function(){
        this.shareMask.active = false;
        if(confige.curOverLayer != -1)
            confige.curOverLayer.openShare();
        if(this.shareLayer != -1)
        {
            this.shareLayer.shareBtn1.interactable = true;
            this.shareLayer.shareBtn2.interactable = true;
        }
    },

    WXCancle:function(){
        this.shareMask.active = false;
        if(confige.curOverLayer != -1)
            confige.curOverLayer.openShare();

        if(this.shareLayer != -1)
        {
            this.shareLayer.shareBtn1.interactable = true;
            this.shareLayer.shareBtn2.interactable = true;
        }
    },

    h5ShareInit:function(){
        var curShareURL = confige.h5ShareUrlNew.replace('ROOMNUM', '0');
        if(confige.h5InviteCode != "0")
        {
            curShareURL += "&invite_code=" + confige.h5InviteCode;
        }
        console.log("H5分享给好友");
        wx.onMenuShareAppMessage({
            title: confige.shareTitle,
            desc: confige.shareDes,
            link: curShareURL,
            imgUrl: confige.h5ShareIco,
            trigger: function(res) {},
            success: function(res) {},
            cancel: function(res) {},
            fail: function(res) {}
        });
        console.log("H5分享到朋友圈2222222");
        wx.onMenuShareTimeline({
            title: confige.shareTitle,
            desc: confige.shareDes,
            link: curShareURL,
            imgUrl: confige.h5ShareIco,
            trigger: function(res) {},
            success: function(res) {},
            cancel: function(res) {},
            fail: function(res) {}
        });
    },

    btnReturnRoomClick:function(){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        var curLastRoomID = cc.sys.localStorage.getItem('lastRoomID');
        var joinCallFunc = function(){
            console.log("onBtnJoinRoom joinCallFunc!!!!!");
            this.loadingLayer.showLoading();
        };
        console.log("fuck roomId");
        console.log(curLastRoomID)
        pomelo.clientSend("join",{"roomId":parseInt(curLastRoomID)}, joinCallFunc);
    },

    hideReturnRoom:function(){
        cc.sys.localStorage.setItem('lastRoomID',0);
    },

    btnJoinMyRoom:function(){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        if(parseInt(confige.userInfo.balcony)){
            pomelo.clientSend("join",{"roomId":parseInt(confige.userInfo.balcony)});
        }else{
            this.clubTips.active = true;
        }
    },
    hideClubTips:function(){
        this.clubTips.active = false;
    },

    showAdminLayer:function(){
        if(confige.userInfo.limits >= 2)
        {
            window.DKTools.audioEG.playEffect("tips_btnClick");
            this.adminLayer.showLayer();
        }else{
            window.clientGlobal.tipsBox.showLayer(1,"您没有该权限!");
        }
    },

    btnAdminLayerClick:function(event, customEventData){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        var index = parseInt(customEventData);
        switch(index){
            case 0:
            pomelo.request("connector.entryHandler.sendData", {"code" : "superOperation","params" : {"cmd" : "getBalconyList"}}, function(data) {
                console.log("getBalconyList flag is : ")
                console.log(data)
            });
            break;
            case 1:
            pomelo.request("connector.entryHandler.sendData", {"code" : "superOperation","params" : {"cmd" : "openBalcony","gameType" : "PaiGowBalcony","uid" : parseInt(this.adminUid.string)}}, function(data) {
                console.log("openBalcony flag is : ")
                console.log(data)
            });
            break;
            case 2:
            pomelo.request("connector.entryHandler.sendData", {"code" : "superOperation","params" : {"cmd" : "closeBalcony ","roomId" : parseInt(this.adminRoomId.string)}}, function(data) {
                console.log("openBalcony flag is : ")
                console.log(data)
            });
            break;
            default:
            break;
        };
        
    },

    showCheckLayer:function(){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        this.identification.showLayer();
    },

    showJoinRoomHistory:function(){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        this.joinRoomHistory.showLayer();
    },

    openShare:function(){
        if(confige.curOverLayer != -1)
            confige.curOverLayer.openShare();
        if(this.shareLayer != -1)
        {
            this.shareLayer.shareBtn1.interactable = true;
            this.shareLayer.shareBtn2.interactable = true;
        }
    },

    WXCancle:function(){
        if(confige.curOverLayer != -1)
            confige.curOverLayer.openShare();

        if(this.shareLayer != -1)
        {
            this.shareLayer.shareBtn1.interactable = true;
            this.shareLayer.shareBtn2.interactable = true;
        }
    },

    hideNoticeLayer:function(){
        this.noticeLayer.active = false;
    },

    hideCreateLayer:function(){
        this.moreGameLayer.active = false;
        this.createLayer.hideLayer();
        this.roomInfoLayer.showLayer();
    },


});